package com.qy.changemachine.util
import android.annotation.SuppressLint
import android.content.Context
import android.os.Environment
import android.util.Log
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import java.util.concurrent.Executors

object LogUtil {

    private const val TAG = "LogUtil"
    private const val LOG_FILE_NAME = "app_log.txt"
    private var logFile: File? = null

    // 单线程池，确保日志写入顺序执行
    private val logExecutor = Executors.newSingleThreadExecutor()

    // 初始化日志文件
    @SuppressLint("SdCardPath")
    fun init(context: Context) {
        if (logFile == null) {
//            val logDir = context.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS)
            logFile = File(Contants.DATA_PATH, LOG_FILE_NAME)
            if (!logFile!!.exists()) {
                try {
                    logFile!!.createNewFile()
                } catch (e: IOException) {
                    Log.e(TAG, "Failed to create log file: ${e.message}")
                }
            }
        }
    }

    // 写入日志到文件
    private fun writeToFile(message: String) {
        logExecutor.execute {
            if (logFile == null) {
                Log.e(TAG, "Log file is not initialized!")
                return@execute
            }

            try {
                val timestamp = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(Date())
                val logMessage = "$timestamp: $message\n"
                FileOutputStream(logFile, true).use { fos ->
                    fos.write(logMessage.toByteArray())
                }
            } catch (e: IOException) {
                Log.e(TAG, "Failed to write log to file: ${e.message}")
            }
        }
    }

    // 封装 Log.d，同时写入文件
    fun d(tag: String, message: String) {
        Log.d(tag, message)
        writeToFile("D/$tag: $message")
    }

    // 封装 Log.e，同时写入文件
    fun e(tag: String, message: String) {
        Log.e(tag, message)
        writeToFile("E/$tag: $message")
    }

    // 封装 Log.i，同时写入文件
    fun i(tag: String, message: String) {
        Log.i(tag, message)
        writeToFile("I/$tag: $message")
    }

    // 封装 Log.w，同时写入文件
    fun w(tag: String, message: String) {
        Log.w(tag, message)
        writeToFile("W/$tag: $message")
    }
}